<?php

namespace app\common\service\GoodsService;

use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsTags;
use app\Normal;
use app\model\BbcModel\GoodsService as Model_GoodsService;
use app\model\BbcModel\BusinessGoods;
use app\model\BbcModel\ChannelBusiness;
use app\model\BbcModel\GoodsClass;
use app\model\BbcModel\GoodsSpecPrice;
use app\model\BbcModel\GoodsBrand;
use app\model\BbcModel\TransitTemplate;
use app\model\BbcModel\Prove;

class GoodsService
{
    public function Fictitious($param){
        if(empty($param['limit'])){
            return Normal::returnCode(Normal::FAIL,'请输入修改条件');
        }
        if(empty($param['start'])){
            return Normal::returnCode(Normal::FAIL,'请输入最低值');
        }
        if(empty($param['end'])){
            return Normal::returnCode(Normal::FAIL,'请输入最大值');
        }
        if($param['start']>=$param['end']){
            return Normal::returnCode(Normal::FAIL,'最大值必须大于最低值');
        }
        if($param['end']>1000){
            return Normal::returnCode(Normal::FAIL,'最大值不能超过1000');
        }
        ini_set('memory_limit','-1');
        $limit = $param['limit'];
        $where = [
            ['cid','=',$param['cid']],
            ['df','=',0],
            ['fictitious_sale','<',$limit],
            '_fields_'=>'id,fictitious_sale'
        ];
        $list = Goods::instance()->lists($where);
        try{
            if(!empty($list)){
                foreach ($list as $v){
                    $num=rand($param['start'],$param['end']);
                    $edit_data[]=[
                        'id'=>$v['id'],
                        'fictitious_sale'=>$num+$v['fictitious_sale']
                    ];
                }
                $res = Goods::instance()->saveAll($edit_data);
            }
            return Normal::returnCode(Normal::SUC,'修改成功');
        }catch(\Exception $e){
            return Normal::returnCode(Normal::FAIL,'修改失败'.$e->getMessage());
        }
    }

    public function serviceLists($param): array
    {
        $page = (isset($param['page']) && $param['page'] != '') ? $param['page'] : 1;
        $limit = (isset($param['limit']) && $param['limit'] != '') ? $param['limit'] : 20;
        $where = [
            ['cid','=',$param['cid']],
            ['cb_id','=',$param['cb_id']],
        ];
        if(isset($param['title']) && $param['title'] != ''){
            $where[] = ['title','like',"%{$param['title']}%"];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['status','=',$param['status']];
        }
        if(isset($param['is_default']) && $param['is_default'] != ''){
            $where[] = ['is_default','=',$param['is_default']];
        }
        $data_lists = Model_GoodsService::instance()->where($where)->order('show_order desc,id desc')->page((int)$page)->limit((int)$limit)->field('id,title,status,is_default,show_order')->select();
        $total = Model_GoodsService::instance()->where($where)->count();
        return Normal::returnCode(Normal::SUC,'获取成功',['total'=>$total,'data_lists'=>$data_lists]);
    }
    
    public function serviceListsNoPage($param): array
    {
        $where = [
            ['cid','=',$param['cid']],
           // ['cb_id','=',$param['cb_id']],
            ['status','=',1],
        ];
        if(isset($param['title']) && !$param['title']){
            $where[] = ['title','like',"%{$param['title']}%"];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['status','=',$param['status']];
        }
        if(isset($param['is_default']) && $param['is_default'] != ''){
            $where[] = ['is_default','=',$param['is_default']];
        }
        $data_lists = Model_GoodsService::instance()->where($where)->order('show_order desc,id desc')->field('id,title,status,is_default,show_order')->select();
        return Normal::returnCode(Normal::SUC,'获取成功',$data_lists);
    }
    

    public function addService($param){
        if(!isset($param['title']) || !$param['title']){
            return Normal::returnCode(Normal::FAIL,'服务标题不能为空');
        }
        if(!isset($param['content'])){
            $param['content'] = '';
        }
        if(!isset($param['show_order'])){
            $param['show_order'] = 0;
        }
        $res = Model_GoodsService::instance()->insert(['cid'=>$param['cid'],'cb_id'=>$param['cb_id'],'title'=>$param['title'],'content'=>$param['content'],'cd'=>time(),'md'=>time(),'show_order'=>$param['show_order']]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'新增失败');
        }
        return Normal::returnCode(Normal::SUC,'新增成功');
    }

    public function serviceInfo($param){
        $info = Model_GoodsService::instance()->info(['id'=>$param['id'],'cid'=>$param['cid'],'_fields_'=>'id,title,content,show_order']);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品服务不存在');
        }
        return Normal::returnCode(Normal::SUC,'获取成功',$info);
    }

    public function editGoodsService($param){
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'服务ID不能为空');
        }
        if(!isset($param['title']) || !$param['title']){
            $param['title'] = '';
        }
        if(!isset($param['content']) || !$param['content']){
            $param['content'] = '';
        }
        if(!isset($param['show_order']) || !$param['show_order']){
            $param['show_order'] = 0;
        }
        $info = Model_GoodsService::instance()->info(['id'=>$param['id'],'cid'=>$param['cid']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品服务不存在');
        }
        $res = Model_GoodsService::instance()->where(['id'=>$param['id']])->update(['title'=>$param['title'],'content'=>$param['content'],'show_order'=>$param['show_order']]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'编辑失败');
        }
        return Normal::returnCode(Normal::SUC,'编辑成功');
    }


    public function changeStatusService($param){
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'服务ID不能为空');
        }
        if(!isset($param['status']) || !in_array($param['status'],[0,1])){
            return Normal::returnCode(Normal::FAIL,'服务切换状态不正确');
        }
        $info = Model_GoodsService::instance()->info(['id'=>$param['id'],'cid'=>$param['cid']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品服务不存在');
        }
        $res = Model_GoodsService::instance()->where(['id'=>$param['id']])->update(['status'=>$param['status']]);
        if($res === false){
            return Normal::returnCode(Normal::FAIL,'操作失败');
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }

    public function changeDefaultService($param){
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'服务ID不能为空');
        }
        if(!isset($param['is_default']) || !in_array($param['is_default'],[0,1])){
            return Normal::returnCode(Normal::FAIL,'服务切换状态不正确');
        }
        $info = Model_GoodsService::instance()->info(['id'=>$param['id'],'cid'=>$param['cid']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品服务不存在');
        }
        $res = Model_GoodsService::instance()->where(['id'=>$param['id']])->update(['is_default'=>$param['is_default']]);
        if($res === false){
            return Normal::returnCode(Normal::FAIL,'操作失败');
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }

    /**
     * 组装查询条件
     * @param array $param
     * @return array
     */
    public function makeWhere(array $param):array
    {
        $where=[];
        $where[]=['g.df','=',0];
        $sql='';
        if(!empty($param['cid'])){
            $where[]=['g.cid','=',$param['cid']];
        }
        if(!empty($param['cb_id'])){
            $cbinfo= ChannelBusiness::instance()->info(['id'=>$param['cb_id']]);
            $where[]=['bs.cid','=',$param['cid']];
            $where[]=['bs.level_id','=',$cbinfo['level_id']];
        }
        if(!empty($param['skucode'])){
            $where[]=['g.skucode','=',$param['skucode']];
        }
        if(!empty($param['keyword'])){
            $where[]=['g.name|g.skucode|g.barcode','like','%'.$param['keyword'].'%'];
        }
        if(!empty($param['barcode'])){
            $where[]=['g.barcode','=',$param['barcode']];
        }
        if(!empty($param['name'])){
            $where[]=['g.name','like','%'.$param['name'].'%'];
        }
        if(!empty($param['origin'])){
            $where[]=['g.origin','like','%'.$param['origin'].'%'];
        }
        if(!empty($param['class_id'])){
            $children = Goodsclass::instance()->where('pid', $param['class_id'])->where(['df'=>0])->column('id');
            $children_2 = GoodsClass::instance()->where('pid','in', $children)->where(['df'=>0])->column('id');
            $class_ids = array_merge($children,$children_2);
            array_push($class_ids,$param['class_id']);
            $where[]=['g.class_id','in',$class_ids];
        }
        if(!empty($param['brand_id'])){
            $where[]=['g.brand_id','=',$param['brand_id']];
        }
        if(isset($param['status']) && $param['status'] !==''){
            $where[] = ['g.status', '=', $param['status']];
        }
        //商品类型
        if(isset($param['is_bonded']) && $param['is_bonded'] !==''){
            $where[] = ['g.is_bonded', '=', $param['is_bonded']];
        }
        //是否有货
        if(isset($param['num_storage']) && $param['num_storage'] !==''){
            if($param['num_storage']==1){
                $where[] = ['g.num_storage', '>', 0];
            }else{
                $where[] = ['g.num_storage', '=', 0];
            }
        }
        //是否有分类
        if (isset($param['is_class']) && $param['is_class'] !== '') {
            if($param['is_class'] == 1){
                $where[] = ['g.class_id', '<>', 0];
            }else{
                $where[] = ['g.class_id', '=', 0];
            }
        }
        //价格控制
//        if (isset($param['medicinal']) && $param['medicinal'] !== '') {
//            $medicinal = $param['medicinal'];
//            $where[] = ['g.clasmedicinals_id', '=', $medicinal];
//        }
        //含税
        if (isset($param['tax_free']) && $param['tax_free'] !='') {
            $where[] = ['g.tax_free', '=', $param['tax_free']];
        }
        //包邮
        if(isset($param['isfree_postfee']) && $param['isfree_postfee'] != ''){
            if($param['isfree_postfee'] == 1){
                $isfree_postfee = 1;
            }else{
                $isfree_postfee = 0;
            }
            $where[] = ['g.isfree_postfee', '=', $isfree_postfee];
        }
        $sql='';
        //供应商标签
        if(isset($param['supply_tag'])){
            if(is_array($param['supply_tag']) && count($param['supply_tag'])>0){
                $supply_tag = $param['supply_tag'];
                $sqltag='';
                foreach ($supply_tag as $key=>$v){
                    if($v){
                        if($key != count($supply_tag) - 1){
                            $sqltag .= " find_in_set($v,supply_tag) or";
                        }else{
                            $sqltag .= " find_in_set($v,supply_tag)";
                        }
                    }
                }
                if($sqltag){
                    $sql.=" (".$sqltag.")";
                }
            }elseif(!empty($param['supply_tag'])){
                $sql.=" find_in_set(".$param['supply_tag'].",supply_tag)";
            }
        }
        return [
            'where'=>$where,
            'sql'=>$sql,
        ];
    }
    
    /**
     * 后台商品列表
     * @param array $param
     * @return array
     */
    public function goodsList(array $param):array {
        $check=$this->makeWhere($param);
        $where=$check['where'];
        $sql=$check['sql'];
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:10;
        $p=($page-1)*$limit;
        if($param['cb_id']>0){
            $dbModel= BusinessGoods::instance()->alias('bs')
                    ->leftjoin('goods g','bs.goods_id=g.id');
        }else{
            $dbModel= Goods::instance()->alias('g');
        }
        $query=$dbModel->field('g.*,gc.name as goods_class_name,gb.name as goods_brand_name')
                ->leftjoin('goods_class gc','gc.id=g.class_id')
                ->leftjoin('goods_brand gb','gb.id=g.brand_id')
                ->where($where);
        if($sql){
           $query=$query->where($sql); 
        }
        $list=$query->order('g.id desc')
                ->limit($p, $limit)
                ->select()
                ->toArray();
        foreach ($list as &$item) {
            if($item['num_storage']>0){
                $item['has_storage']='是';
            }else{
                $item['has_storage']='否';
            }
            $item['is_bonded_name']= Goods::instance()->is_bonded[$item['is_bonded']];
            $item['cd']=$item['cd']?date('Y-m-d H:i:s',$item['cd']):'';
            $item['md']=$item['md']?date('Y-m-d H:i:s',$item['md']):'';
            $item['status_name']=$item['status']==0?'下架':'上架';
        }
        $total=$query->count();
        $data['total']=$total;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
        
    }
    
    /**
     * 获取商品详情
     * @param array $param
     * @return array
     */
    public function getGoodsDetail(array $param):array {
        if (empty($param['id'])) {
            return Normal::returnCode(Normal::FAIL,"id必传");
        }
        if($param['cb_id']>0){
            $cbinfo= ChannelBusiness::instance()->info(['id'=>$param['cb_id']]);
            $bg= BusinessGoods::instance()->info(['goods_id'=>$param['id'],'level_id'=>$cbinfo['level_id']]);
            if(!$bg){
                return Normal::returnCode(Normal::FAIL,"当前渠道没有该商品");
            }
        }
        $goodsinfo= Goods::instance()->info(['id'=>$param['id'],'cid'=>$param['cid']]);
        if(!$goodsinfo){
            return Normal::returnCode(Normal::FAIL,"未找到相关商品");
        }
        $spec_price= GoodsSpecPrice::instance()->lists(['goods_id'=>$goodsinfo['id'],'_order_'=>'spec_num asc']);
        $goodsinfo['spec_price']=$spec_price;
        if($goodsinfo['num_storage']>0){
            $goodsinfo['has_storage']='是';
        }else{
            $goodsinfo['has_storage']='否';
        }
        $goodsband= GoodsBrand::instance()->info(['id'=>$goodsinfo['brand_id']]);
        $goodsinfo['brand_name']=$goodsband['name']??'';
        $goodsclass= GoodsClass::instance()->info(['id'=>$goodsinfo['class_id']]);
        $goodsinfo['class_name']=$goodsclass['name']??'';
        $goodsinfo['is_bonded_name']= Goods::instance()->is_bonded[$goodsinfo['is_bonded']];
        $goodsinfo['cd']=$goodsinfo['cd']?date('Y-m-d H:i:s',$goodsinfo['cd']):'';
        $goodsinfo['md']=$goodsinfo['md']?date('Y-m-d H:i:s',$goodsinfo['md']):'';
        $goodsinfo['status_name']=$goodsinfo['status']==0?'下架':'上架';
        $supply_tagname='';
        $tagname='';
        if($goodsinfo['supply_tag']){
            $supplytags= GoodsTags::instance()->where([['type','=',0],['id','in',$goodsinfo['supply_tag']]])->column('name');
            $supply_tagname = $supplytags ? implode(',', $supplytags) :'';
        }
        if($goodsinfo['tag']){
            $tags = GoodsTags::instance()->where([['type','=',0],['id','in',$goodsinfo['tag']]])->column('name');
            $tagname = $tags ? implode(',', $tags) : '';
        }
        $goodsinfo['supply_tag_array']=$goodsinfo['supply_tag']?explode(',', $goodsinfo['supply_tag']):[];
        $goodsinfo['supply_tag_name']=$supply_tagname;
        $goodsinfo['tag_name']=$tagname;
        $goodsservice= Model_GoodsService::instance()->lists([['id','in',$goodsinfo['service_id']]]);
        $goodsinfo['service_name']=$goodsservice??[];
        $TransitTemplate= TransitTemplate::instance()->info(['id'=>$goodsinfo['template_id']]);
        $goodsinfo['transit_template']=$TransitTemplate??[];
        $goodsinfo['weight']=$goodsinfo['weight']?bcdiv($goodsinfo['weight'], 1000,2):0;

        $goodsinfo['goods_tag'] = $goodsinfo['goods_tag']?json_decode($goodsinfo['goods_tag'],true):[];
        $prove_name='';
        if($goodsinfo['prove_id']){
            $prove= Prove::instance()->info(['id'=>$goodsinfo['prove_id']]);
            $prove_name=$prove['name']??'';
        }
        $goodsinfo['prove_name']=$prove_name;
        $goodsinfo['tax_rate'] = $goodsinfo['tax_rate'] * 100;
        return Normal::returnCode(Normal::SUC,"请求成功",$goodsinfo);
    }
    
    /**
     * 设置运费模板
     * @param array $param
     * @return array
     */
    public function set_template(array $param):array {
        if(!$param['template_id']){
            return Normal::returnCode(Normal::FAIL,"请选择运费模板");
        }
        if($param['cb_id']>0){
            return Normal::returnCode(Normal::FAIL,"不支持该功能");
        }
        $temp=TransitTemplate::instance()->info(['id'=>$param['template_id'],'cid'=>$param['cid'],'df'=>0]);
        if(!$temp){
            return Normal::returnCode(Normal::FAIL,"运费模板不存在");
        }
        $check = $this->makeWhere($param);
        $dbModel= Goods::instance()->alias('g')->where($check['where']);
        if($check['sql']){
            $dbModel=$dbModel->where($check['sql']);
        }
        
        $res = $dbModel->update(['template_id'=>$param['template_id'],'md'=>time()]);
        if($res === false){
            return Normal::returnCode(Normal::FAIL,"设置失败");
        }
        return Normal::returnCode(Normal::SUC,"设置成功");
    }
    
    /**
     * 设置商品服务
     * @param array $param
     * @return array
     */
    public function setService(array $param):array
    {
        if(!$param['goods_service']){
            return Normal::returnCode(Normal::FAIL,"请选择商品服务");
        }
        if($param['cb_id']>0){
            return Normal::returnCode(Normal::FAIL,"不支持该功能");
        }
        $check = $this->makeWhere($param);
        $dbModel= Goods::instance()->alias('g')->where($check['where']);
        if($check['sql']){
            $dbModel=$dbModel->where($check['sql']);
        }
        $ids=implode(',',$param['goods_service']);
        $res = $dbModel->update(['service_id'=>$ids,'md'=>time()]);
        if($res === false){
            return Normal::returnCode(Normal::FAIL,"设置失败");
        }
        return Normal::returnCode(Normal::SUC,"设置成功");
    }
    
    /**
     * 上下架商品
     * @param array $param
     * @return array
     */
    public function upDownGoods(array $param):array {
        if(!$param['id']){
            return Normal::returnCode(Normal::FAIL,"缺少商品id");
        }
        if (isset($param['status'])&&$param['status']!=='') {
        }else{
            return Normal::returnCode(Normal::FAIL,"status必传");
        }
        $goods=Goods::instance()->info(['id'=>$param['id']]);
        if(!$goods){
            return Normal::returnCode(Normal::FAIL,"未找到商品");
        }
        $ChannelEsService=new ChannelEsService();
        if($param['status']==0){
            $businessGoods=BusinessGoods::instance()->lists(['goods_id'=>$param['id'],'_fields_'=>'id']);
            $es=[];
            foreach ($businessGoods as $keys=>$values){
                $businessDeleteItem['id']=$values['id'];
                $es[]=$businessDeleteItem;
            }
            $ChannelEsService->pushNew($es,'channel','delete');
        }else{
            $brand=GoodsBrand::instance()->info(['id'=>$goods['brand_id']]);
            $businessGoods=BusinessGoods::instance()->lists(['goods_id'=>$param['id']]);
            $channel=[];
            $idxData['goodsId']=$goods['id'];
            $idxData['name']=$goods['name'];
            $idxData['classifyID']=$goods['class_id'];
            $idxData['brandName']=$brand['BrandName']??'';
            $idxData['isActive']=true;
            foreach ($businessGoods as $v){
                $idxData['id']=$v['id'];
                $idxData['channelID']=$v['level_id'];
                $channel[]=$idxData;
            }
            $ChannelEsService->pushNew($channel,'channel','insert');
        }
        $result=Goods::instance()->edit(['id'=>$param['id']],['status'=>$param['status'],'md'=>time()]);
        if($result){
            return Normal::returnCode(Normal::SUC,"设置成功");
        }else{
            return Normal::returnCode(Normal::FAIL,"设置失败");
        }
    }

    /**
     * 批量上下架
     * @param array $param
     * @return array
     */
    public function upDownGoodsMany(array $param):array {
        if (isset($param['op'])&&$param['op']!=='') {
        }else{
            return Normal::returnCode(Normal::FAIL,"op必传");
        }
        $check=$this->makeWhere($param);
        $where=$check['where'];
        $sql=$check['sql'];
        if($param['cb_id']>0){
            $dbModel= BusinessGoods::instance()->alias('bs')
                ->leftjoin('goods g','bs.goods_id=g.id');
        }else{
            $dbModel= Goods::instance()->alias('g');
        }
        $query=$dbModel->field('g.id,gb.name as goods_brand_name,g.class_id,g.name')
            ->leftjoin('goods_brand gb','gb.id=g.brand_id')
            ->where($where);
        if($sql){
            $query=$query->where($sql);
        }
        $list=$query->select()->toArray();
        if(empty($list)){
            return Normal::returnCode(Normal::FAIL,"未找到商品");
        }
        $ids=array_column($list,'id');
        $goodsIndex=array_column($list,null,'id');
        $ChannelEsService=new ChannelEsService();
        if($param['op']==0){
            $businessGoods=BusinessGoods::instance()->lists(['goods_id'=>$ids,'_fields_'=>'id']);
            $es=[];
            foreach ($businessGoods as $keys=>$values){
                $businessDeleteItem['id']=$values['id'];
                $es[]=$businessDeleteItem;
            }
            $ChannelEsService->pushNew($es,'channel','delete');
        }else{
            $businessGoods=BusinessGoods::instance()->lists(['goods_id'=>$ids]);
            $channel=[];
            $idxData['isActive']=true;
            foreach ($businessGoods as $v){
                $idxData['goodsId']=$v['goods_id'];
                $idxData['id']=$v['id'];
                $idxData['channelID']=$v['level_id'];
                $idxData['name']=$goodsIndex[$v['goods_id']]['name'];
                $idxData['classifyID']=$goodsIndex[$v['goods_id']]['class_id'];
                $idxData['brandName']=$goodsIndex[$v['goods_id']]['goods_brand_name'];
                $channel[]=$idxData;
            }
            $ChannelEsService->pushNew($channel,'channel','insert');
        }
        $result=Goods::instance()->edit(['id'=>$ids],['status'=>$param['op'],'md'=>time()]);
        if($result){
            return Normal::returnCode(Normal::SUC,"设置成功");
        }else{
            return Normal::returnCode(Normal::FAIL,"设置失败");
        }
    }

    
    /**
     * 修改商品资料(根据id修改运费模板、服务、证明、商品标签)
     * @param array $param
     * @return array
     */
    public function editGoods(array $param):array {
        if(!$param['id']){
            return Normal::returnCode(Normal::FAIL,"缺少商品id");
        }
        $goods=Goods::instance()->info(['id'=>$param['id']]);
        if(!$goods){
            return Normal::returnCode(Normal::FAIL,"未找到商品");
        }
        if($param['cb_id']>0){
            return Normal::returnCode(Normal::FAIL,"不支持该功能");
        }
        $edit=['md'=>time()];
        if($param['goods_service']){
            $service_ids=implode(',',$param['goods_service']);
            $edit['service_id']=$service_ids;
        }
        if($param['template_id']){
            $edit['template_id']=$param['template_id'];
        }
        if(isset($param['goods_tag'])){
            $goods_tags= json_encode($param['goods_tag'],JSON_UNESCAPED_UNICODE);
            $edit['goods_tag']=$goods_tags;
        }
        if($param['prove_id']){
            $edit['prove_id']=$param['prove_id'];
        }
        $result=Goods::instance()->edit(['id'=>$param['id']],$edit);
        if($result){
            return Normal::returnCode(Normal::SUC,"修改成功");
        }else{
            return Normal::returnCode(Normal::FAIL,"修改失败");
        }
    }
}